package authblog

import (
	"context"
	"errors"

	"blogcenter/internal/svc"
	"blogcenter/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetBlogListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetBlogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBlogListLogic {
	return &GetBlogListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetBlogListLogic) GetBlogList(req *types.BlogListRequest) (resp *types.BlogListResponse, err error) {
	// 参数校验
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.Size <= 0 || req.Size > 100 {
		req.Size = 10
	}

	// 获取分页数据（不需要用户ID过滤）
	blogs, total, err := l.svcCtx.BlogModel.FindWithPage(l.ctx, req.Page, req.Size)
	if err != nil {
		logx.Errorf("查询博客列表失败: %v", err)
		return nil, errors.New("获取博客列表失败")
	}

	// 构造响应数据
	resp = &types.BlogListResponse{
		BaseResponse: types.BaseResponse{
			Code:    200,
			Message: "获取成功",
		},
		Data: make([]types.Blog, 0, len(blogs)),
		Pagination: types.Pagination{
			Page:  req.Page,
			Size:  req.Size,
			Total: int(total),
		},
	}

	for _, blog := range blogs {
		_, images, err := l.svcCtx.BlogModel.FindWithImages(l.ctx, blog.ID)
		if err != nil {
			logx.Errorf("获取博客图片失败, blogId: %d, error: %v", blog.ID, err)
			continue
		}

		resp.Data = append(resp.Data, types.Blog{
			Id:         int(blog.ID),
			Title:      blog.Title,
			Content:    "", // 列表页不返回完整内容
			LikeNum:    blog.LikeNum,
			CommentNum: blog.CommentNum,
			Place:      blog.Place,
			JoyNum:     blog.JoyNum,
			JoyFeeling: blog.JoyFeeling,
			CreateTime: blog.CreatedAt.Format("2006-01-02 15:04:05"),
			Photo: types.PhotoData{
				Url: images,
			},
			UserId: blog.UserId,
		})
	}

	return resp, nil
}
